package com.quectel.core.module.carparking.service.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.carparking.dao.CarParkingSpaceDao;
import com.quectel.core.module.carparking.dto.CarParkingSpaceDto;
import com.quectel.core.module.carparking.dto.CarParkingSpaceLogDto;
import com.quectel.core.module.carparking.entity.CarParkingSpaceEntity;
import com.quectel.core.module.carparking.service.CarParkingService;
import com.quectel.core.module.carparking.service.CarParkingSpaceLogService;
import com.quectel.core.module.carparking.service.CarParkingSpaceService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @author bobo
 * @email bob.yu@quectel.com
 * @date 2022/02/22 09:45
 */
@DubboService
public class CarParkingSpaceServiceImpl implements CarParkingSpaceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CarParkingSpaceServiceImpl.class);

    private static final Function<Long, String> CAR_PARKING_SPACE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "CAR_PARKING_SPACE_CACHE_BY_ID:%d", id);
    private static final Function<Long, String> CAR_PARKING_SPACE_CACHE_BY_PARK_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "CAR_PARKING_SPACE_CACHE_BY_PARK_ID:%d", id);

    @Autowired
    private CarParkingSpaceDao carParkingSpaceDao;
    @Autowired
    private CarParkingService carParkingService;
    @Autowired
    private VillageRoomService roomService;
    @Autowired
    private VillageService villageService;
    @Autowired
    private CarParkingSpaceLogService carParkingSpaceLogService;

    @Override
    public List<CarParkingSpaceDto> byCardLeased(String mobile) {
        List<CarParkingSpaceEntity> carParkingSpaceEntities = carParkingSpaceDao.byCardLeased(mobile);
        List<CarParkingSpaceDto> carParkingSpaceDtos = new ArrayList<>();
        for (CarParkingSpaceEntity carParkingSpaceEntity : carParkingSpaceEntities) {
            CarParkingSpaceDto carParkingSpaceDto = CopyUtils.copyObj(carParkingSpaceEntity, CarParkingSpaceDto.class);
            carParkingSpaceDto.setBuyTime(DateUtil.beginOfDay(carParkingSpaceEntity.getLeaseTime()));
            paddingField(carParkingSpaceDto);
            carParkingSpaceDtos.add(carParkingSpaceDto);
        }
        return carParkingSpaceDtos;
    }

    /**
     * 保存操作日志
     */
    public void saveCarParkingSpaceChangeLog(CarParkingSpaceDto carParkingSpaceDto) {
        CarParkingSpaceLogDto carParkingSpaceLogDto = new CarParkingSpaceLogDto();
        carParkingSpaceLogDto.setCarPakingSpaceId(carParkingSpaceDto.getId());
        carParkingSpaceLogDto.setCarParkingSpaceState(carParkingSpaceDto.getState());
        carParkingSpaceLogDto.setHouseholdName(carParkingSpaceDto.getHouseholdName());
        carParkingSpaceLogDto.setHouseholdRoomId(carParkingSpaceDto.getHouseholdRoomId());
        carParkingSpaceLogDto.setHouseholdRoomName(carParkingSpaceDto.getHouseholdRoomName());
        carParkingSpaceLogDto.setMobile(carParkingSpaceDto.getMobile());
        carParkingSpaceLogDto.setLicenses(carParkingSpaceDto.getLicenses());
        carParkingSpaceLogDto.setCreateTime(new Date());
        carParkingSpaceLogService.save(carParkingSpaceLogDto);
    }

    @Override
    public List<CarParkingSpaceDto> selectCacheByVillageId(Long villageId) {
        return CacheKit.cacheToRedis(
                () -> selectByVillageId(villageId),
                CAR_PARKING_SPACE_CACHE_BY_PARK_ID_FUNC.apply(villageId),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public List<CarParkingSpaceDto> selectByVillageId(Long villageId) {
        List<CarParkingSpaceEntity> carParkingSpaceEntities = carParkingSpaceDao.selectList(new LambdaQueryWrapper<CarParkingSpaceEntity>()
                .eq(CarParkingSpaceEntity::getVillageId, villageId));
        return CopyUtils.copyList(carParkingSpaceEntities, CarParkingSpaceDto.class);
    }

    @Override
    public CarParkingSpaceDto selectOne(Long carParkingId, String code) {
        CarParkingSpaceEntity entity = carParkingSpaceDao.selectOne(
                new LambdaQueryWrapper<CarParkingSpaceEntity>()
                        .eq(CarParkingSpaceEntity::getCarParkingId, carParkingId)
                        .eq(CarParkingSpaceEntity::getCode, code)
        );
        return paddingField(CopyUtils.copyObj(entity, CarParkingSpaceDto.class));
    }

    @Override
    public CarParkingSpaceDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                CAR_PARKING_SPACE_CACHE_BY_ID_FUNC.apply(id),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public CarParkingSpaceDto selectById(Long id) {
        CarParkingSpaceEntity entity = carParkingSpaceDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, CarParkingSpaceDto.class));
    }

    @Override
    public List<CarParkingSpaceDto> queryList(Map<String, Object> params) {
        List<CarParkingSpaceEntity> list = carParkingSpaceDao.queryList(params);
        List<CarParkingSpaceDto> result = CopyUtils.copyList(list, CarParkingSpaceDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private CarParkingSpaceDto paddingField(CarParkingSpaceDto dto) {
        if (dto != null) {
            VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
            dto.setVillage(villageDto);
            if (villageDto != null) {
                dto.setParkName(villageDto.getName() + "停车场");
            }

            dto.setCarParking(carParkingService.selectCacheById(dto.getCarParkingId()));
            dto.setRoom(roomService.selectCacheById(dto.getHouseholdRoomId()));
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return carParkingSpaceDao.queryTotal(params);
    }

    @Override
    public Long save(CarParkingSpaceDto dto) {
        CarParkingSpaceEntity entity = CopyUtils.copyObj(dto, CarParkingSpaceEntity.class);
        entity.setId(Snowflake.nextId());
        carParkingSpaceDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(CarParkingSpaceDto dto) {
        CarParkingSpaceEntity entity = CopyUtils.copyObj(dto, CarParkingSpaceEntity.class);
        carParkingSpaceDao.updateById(entity);
        CacheKit.invalidRedisCache(CAR_PARKING_SPACE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void updateAllColumnById(CarParkingSpaceDto dto) {
        CarParkingSpaceEntity entity = CopyUtils.copyObj(dto, CarParkingSpaceEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, carParkingSpaceDao);

        CacheKit.invalidRedisCache(CAR_PARKING_SPACE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void deleteById(Long id) {
        carParkingSpaceDao.deleteById(id);

        CacheKit.invalidRedisCache(CAR_PARKING_SPACE_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
